package com.worksystem.Dao;

import java.util.HashMap;
import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Component;

import com.worksystem.entity.Comment;
import com.worksystem.entity.PageBean;
import com.worksystem.entity.Subject;
import com.worksystem.entity.Task;
import com.worksystem.entity.User;

@SuppressWarnings("unchecked")
@Component("taskDao")
public class TaskDaoImp extends BaseDao<Task> implements TaskDao{

	public TaskDaoImp() {
		super(Task.class);
	}

	/*@Autowired
	private SessionFactory sessionFactory ;
	*/
	@Override
	public PageBean getStudentTasklist(User user,Integer pageid) {
		String hql="select t from Task as t,Pokermans as p "
				+ "where p.user.uid=:uid and t.tid=p.task.tid";
		String rowscount="select count(*) from Task as t,Pokermans as p "
				+ "where p.user.uid=:uid and t.tid=p.task.tid";
		Long count=Long.parseLong(getSession().createQuery(rowscount).setParameter("uid", user.getUid()).uniqueResult().toString());
		PageBean pagebean = initPageBean(pageid, count);
		pagebean.setList(getSession().createQuery(hql).setParameter("uid", user.getUid()).setFirstResult((pagebean.getCurrentPage()-1)*pagebean.getPageSize()).setMaxResults(pagebean.getPageSize()).list());
		return pagebean;
	}
	@Override
	public PageBean getTeacherTasklist(User user,Integer pageid){
		String hql="from Task where user.uid=:uid";
		String rowscount="select count(*) from Task where user.uid=:uid";
		Long count=Long.parseLong(getSession().createQuery(rowscount).setParameter("uid", user.getUid()).uniqueResult().toString());
		HashMap<String, Object> parameter=new HashMap<String, Object>();
		parameter.put("uid", user.getUid());
		PageBean pagebean = initPageBean(pageid,count);
		pagebean.setList(getSession().createQuery(hql).setParameter("uid", user.getUid()).setFirstResult((pagebean.getCurrentPage()-1)*pagebean.getPageSize()).setMaxResults(pagebean.getPageSize()).list());
		return pagebean;
	}
	
	@Override
	public User getUserByTaskId(int tid) {
		String hql="select Task.user from Task  where tid=:tid";
		Query query=getSession().createQuery(hql).setParameter("tid", tid);
		User user=(User) query.uniqueResult();
		return user;
	}

	@Override
	public Task getTaskById(Integer id) {
		Task task=(Task) getSession().get(Task.class, id);
		return task;
	}

	@Override
	public List<Comment> getCommentsByTaskId(Integer id) {
		String hql="from Comment where task.tid=:tid";
		
		List<Comment> comments=getSession().createQuery(hql).setParameter("tid", id).list();
		return comments;
	}

	@Override
	public void saveComment(Comment comment) {
		getSession().save(comment);
		Task task=comment.getTask();
		task=getTaskById(task.getTid());
		//评论+1
		System.out.println("当前评论数"+task.getComment()+"评论+1");
		task.setComment(task.getComment()+1);
		//更新任务
		getSession().update(task);
		getSession().flush();
	}
	
	@Override
	public Integer inserttask(Task task,Object[] pokermanids,Object[] subjectids){
		getSession().beginTransaction();
		try {
			System.out.println(task);
			save(task);
			Integer tid=task.getTid();
			//插入关注人
			for (Object uid : pokermanids) {
				String sql="INSERT INTO POKERMANS(PID,USER,TASK) VALUES (NULL, '"+uid+"', '"+tid+"')";
				if(getSession().createSQLQuery(sql).executeUpdate()>0){
					System.out.println("插入关注人成功");
				}
				else{
					System.out.println("插入关注人失败，返回错误代码104");
					return 104;
				}
			}
			//插入任务和试卷的关联
			if(subjectids!=null){
				for(Object subid : subjectids){
					String sql="INSERT INTO tos (SID, TID) VALUES ('"+subid+"', '"+task.getTid()+"')";
					if(getSession().createSQLQuery(sql).executeUpdate()>0){
						System.out.println("插入试卷任务关联成功");
					}
					else{
						System.out.println("插入试卷任务关联失败，返回错误代码107");
						return 107;
					}
				}
			}
			getSession().getTransaction().commit();
		} catch (Exception e) {
			System.out.println("插入任务失败，返回代码103"+e.getMessage());
			getSession().getTransaction().rollback();
			return 103;
		}
		return 1;
	}
	
	@Override
	public Integer deletetask(Integer tid){
		//Task task=getTaskById(tid);
		getSession().beginTransaction();
		try {
			String hql="delete Comment where task.tid=:tid";
			String pokermanhql="delete Pokermans where task.tid=:tid";
			getSession().createQuery(pokermanhql).setParameter("tid", tid).executeUpdate();
			getSession().createQuery(hql).setParameter("tid", tid).executeUpdate();
			String hql2="delete Task where tid=:tid ";
			getSession().createQuery(hql2).setParameter("tid", tid).executeUpdate();
			getSession().getTransaction().commit();
			return 1;
		} catch (Exception e) {
			System.out.println("任务删除失败，返回错误105");
			getSession().getTransaction().rollback();
			return 105;
		}
	}
	
	@Override
	public Integer updatetask(Task task,Object[] pokermanids){
		//首先删除pokermans里面的关注列表，然后再赋值新的进去
		getSession().beginTransaction();
		try {
			getSession().saveOrUpdate(task);
			getSession().flush();
			//删除
			String pokermanhql="delete Pokermans where task.tid=:tid";
			getSession().createQuery(pokermanhql).setParameter("tid", task.getTid()).executeUpdate();
			//插入
			for (Object uid : pokermanids) {
				String sql="INSERT INTO POKERMANS(PID,USER,TASK) VALUES (NULL, '"+uid+"', '"+task.getTid()+"')";
				if(getSession().createSQLQuery(sql).executeUpdate()>0){
					System.out.println("插入关注人成功");
				}
				else{
					System.out.println("插入关注人失败，返回错误代码104");
					return 104;
				}
			}
			getSession().getTransaction().commit();
		} catch (Exception e) {
			System.out.println("更新任务失败，返回错误代码106");
			getSession().getTransaction().rollback();
			return 106;
		}
		return 1;
	}
	@Override
	public List<Subject> getTosByTaskId(Integer tid){
		String hql="select s from Tos as t,Subject s where t.task.tid=:tid and t.subject.id=s.id";
		return getSession().createQuery(hql).setParameter("tid", tid).list();
	}
	
	public List<Subject> getSubjectsByClassId(Integer classId){
		String hql="from Subject where classes.cid=:classId";
		return getSession().createQuery(hql).setParameter("classId", classId).list();
	}
}
